/**  
 * @class Ext.tree.TreeCheckNodeUI  
 * @extends Ext.tree.TreeNodeUI  
 *   
 * 对 Ext.tree.TreeNodeUI 进行checkbox功能的扩展,后台返回的结点信息不用非要包含checked属性  
 *   
 * 扩展的功能点有：  
 * 一、支持只对树的叶子进行选择  
 *    只有当返回的树结点属性leaf = true 时，结点才有checkbox可选  
 *    使用时，只需在声明树时，加上属性 onlyLeafCheckable: true 既可，默认是false  
 *   
 * 二、支持对树的单选  
 *    只允许选择一个结点  
 *    使用时，只需在声明树时，加上属性 checkModel: "single" 既可  
 *   
 * 二、支持对树的级联多选   
 *    当选择结点时，自动选择该结点下的所有子结点，以及该结点的所有父结点（根结点除外），特别是支持异步，当子结点还没显示时，会从后台取得子结点，然后将其选中/取消选中  
 *    使用时，只需在声明树时，加上属性 checkModel: "cascade" 既可  
 *   
 * 三、添加"check"事件  
 *    该事件会在树结点的checkbox发生改变时触发  
 *    使用时，只需给树注册事件,如：  
 *    tree.on("check",function(node,checked){...});  
 *   
 * 默认情况下，checkModel为'multiple'，也就是多选，onlyLeafCheckable为false，所有结点都可选  
 *   
 * 使用方法：在loader里加上 baseAttrs:{uiProvider:Ext.tree.TreeCheckNodeUI} 既可.  
 * 例如：  
 *   var tree = new Ext.tree.TreePanel({  
 *      el:'tree-ct',  
 *      width:568,  
 *      height:300,  
 *      checkModel: 'cascade',   //对树的级联多选  
 *      onlyLeafCheckable: false,//对树所有结点都可选  
 *      animate: false,  
 *      rootVisible: false,  
 *      autoScroll:true,  
 *      loader: new Ext.tree.DWRTreeLoader({  
 *          dwrCall:Tmplt.getTmpltTree,  
 *          baseAttrs: { uiProvider: Ext.tree.TreeCheckNodeUI } //添加 uiProvider 属性  
 *      }),  
 *      root: new Ext.tree.AsyncTreeNode({ id:'0' })  
 *  });  
 *  tree.on("check",function(node,checked){alert(node.text+" = "+checked)}); //注册"check"事件  
 *  tree.render();  
 *   
 */  
  
Ext.tree.TreeCheckNodeUI = function() {   
    //'multiple':多选; 'single':单选; 'cascade':级联多选   
    this.checkModel = 'multiple';   
       
    //only leaf can checked   
    this.onlyLeafCheckable = false;   
       
    Ext.tree.TreeCheckNodeUI.superclass.constructor.apply(this, arguments);   
};   
function getCursorPos(obj){
    obj.focus();
    obj.select();
//    alert(document.selection.createRange());
//    var currentRange=document.selection.createRange();
//    var workRange=currentRange.duplicate();
    obj.select();
//    var allRange=document.selection.createRange();
//    var pos=0;
//    while(workRange.compareEndPoints("StartToStart",allRange)>0) {
//        workRange.moveStart("character",-1);
//        pos++;
//    }
//    currentRange.select();
//    return pos;
}

function onFocus(obj) {
	if(obj.value == '请自定义快捷方式名称') {
		obj.value = '' ;
		if (Ext.isIE) {
			window.event.cancelBubble = true;
		}
	}
	//obj.focus();
	//obj.select();
}

function setCursorPos(obj,pos) {
    var rng =obj.createTextRange();
    rng.moveStart('character',pos);
    rng.collapse(true);
    rng.select();
}
function replaceAndSetPos(obj){
//    if(event.altKey||event.ctrlKey||event.keyCode==16||event.keyCode==17||event.keyCode==18||(event.shiftKey&&event.keyCode==36))
//        return;
    var pos = getCursorPos(obj);
    var temp = obj.value;
    obj.value = obj.value.replace(/[^a-zA-Z0-9\u4E00-\u9FA5\s]*/g,'');
    obj.value = obj.value.replace(/[\s]*$/,'');
    obj.value = obj.value.replace(/^[\s]*/,'');
   // pos = pos - (temp.length - obj.value.length);
    //setCursorPos(obj,pos);
}

Ext.extend(Ext.tree.TreeCheckNodeUI, Ext.tree.TreeNodeUI, {   
  
    renderElements : function(n, a, targetNode, bulkRender){   
        var tree = n.getOwnerTree();   
        this.checkModel = tree.checkModel || this.checkModel;   
        this.onlyLeafCheckable = tree.onlyLeafCheckable || false;   
           
        // add some indent caching, this helps performance when rendering a large tree   
        this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';   
        //console.debug("node:",n);
        var cb = false;
        if(n.attributes && n.attributes.leaf){
            cb=true;
        }
        var href = a.href ? a.href : Ext.isGecko ? "" : "#";   
        var buf = ['<li class="x-tree-node"><div ext:tree-node-id="',n.id,'" class="x-tree-node-el x-tree-node-leaf x-unselectable ', a.cls,'" unselectable="on">',   
            '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",   
            '<img src="', this.emptyIcon, '" class="x-tree-ec-icon x-tree-elbow" />',   
            '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',   
            cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : '/>')) : '',   
            '<a hidefocus="on" class="x-tree-node-anchor" href="',href,'" tabIndex="1" ',   
             a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", '><span unselectable="on">',n.text,'&nbsp;</span></a>',
            cb ? ('<input type=\'text\' onfocus="onFocus(this)"  onblur="if (this.value == \'\') {this.value = \'请自定义快捷方式名称\';}" id="'+n.id+'-alias" value="'+((a.shortcutAlias && a.shortcutAlias != null && a.shortcutAlias != "none") ? a.shortcutAlias : '请自定义快捷方式名称')+'" maxlength="10" onkeyup="replaceAndSetPos(this)" style="width:140px;font-size:10px;display:'+(a.checked ? 'none' : 'none')+'" />') : '',
             '</div>',
            '<ul class="x-tree-node-ct" style="display:none;"></ul>',   
            "</li>"].join('');   
            
         //  alert(buf);
  
        var nel;   
        if(bulkRender !== true && n.nextSibling && (nel = n.nextSibling.ui.getEl())){   
            this.wrap = Ext.DomHelper.insertHtml("beforeBegin", nel, buf);   
        }else{   
            this.wrap = Ext.DomHelper.insertHtml("beforeEnd", targetNode, buf);   
        }   
           
        this.elNode = this.wrap.childNodes[0];   
        this.ctNode = this.wrap.childNodes[1];   
        var cs = this.elNode.childNodes;   
        this.indentNode = cs[0];   
        this.ecNode = cs[1];   
        this.iconNode = cs[2];   
        var index = 3;   
        if(cb){   
            this.checkbox = cs[3];   
            Ext.fly(this.checkbox).on('click', this.check.createDelegate(this,[null]));   
            index++;   
        }   
        this.anchor = cs[index];   
        this.textNode = cs[index].firstChild;   
        n.expand();    //add by zhangzaiyun 904176 解决 没打开节点的情况下，子节点不能被初始化的问题  
    },   
       
    // private   
    check : function(checked){   
        var n = this.node;   
        var tree = n.getOwnerTree();   
        this.checkModel = tree.checkModel || this.checkModel;   
           
        if( checked === null ) {   
            checked = this.checkbox.checked;   
        } else {   
            this.checkbox.checked = checked;   
        }   
           
        n.attributes.checked = checked;   
        tree.fireEvent('check', n, checked);   
           
        if(!this.onlyLeafCheckable && this.checkModel == 'cascade'){   
            var parentNode = n.parentNode;   
            if(parentNode !== null) {   
                this.parentCheck(parentNode,checked);   
            }   
            if( !n.expanded && !n.childrenRendered ) {   
                n.expand(false,false,this.childCheck);   
            }   
            else {   
                this.childCheck(n);   
            }   
        }else if(this.checkModel == 'single'){   
            var checkedNodes = tree.getChecked();   
            for(var i=0;i<checkedNodes.length;i++){   
                var node = checkedNodes[i];   
                if(node.id != n.id){   
                    node.getUI().checkbox.checked = false;   
                    node.attributes.checked = false;   
                    tree.fireEvent('check', node, false);   
                }   
            }   
        }   
           
    },   
       
    // private   
    childCheck : function(node){   
        var a = node.attributes;   
        if(!a.leaf) {   
            var cs = node.childNodes;   
            var csui;   
            for(var i = 0; i < cs.length; i++) {   
                csui = cs[i].getUI();   
                if(csui.checkbox.checked ^ a.checked)   
                    csui.check(a.checked);   
            }   
        }   
    },   
       
    // private   
    parentCheck : function(node ,checked){   
        var checkbox = node.getUI().checkbox;   
        if(typeof checkbox == 'undefined')return ;   
        if(!(checked ^ checkbox.checked))return;   
        if(!checked && this.childHasChecked(node))return;   
        checkbox.checked = checked;   
        node.attributes.checked = checked;   
        node.getOwnerTree().fireEvent('check', node, checked);   
           
        var parentNode = node.parentNode;   
        if( parentNode !== null){   
            this.parentCheck(parentNode,checked);   
        }   
    },   
       
    // private   
    childHasChecked : function(node){   
        var childNodes = node.childNodes;   
        if(childNodes || childNodes.length>0){   
            for(var i=0;i<childNodes.length;i++){   
                if(childNodes[i].getUI().checkbox.checked)   
                    return true;   
            }   
        }   
        return false;   
    },   
       
    toggleCheck : function(value){   
        var cb = this.checkbox;   
        if(cb){   
            var checked = (value === undefined ? !cb.checked : value);   
            this.check(checked);   
        }   
    }   
});  

function shortCutLink(url,id,topMenuId){
	var portal  =   Ext.getCmp('std-panel');  
	//刷新点击的菜单的顶层菜单的样式
	var tbars=portal.tbar; 	
	Ext.each(tbars.items.items,function(tbar){
	   if(typeof(tbar)!='undefined'){
	    tbar.setDisabled(false);
	     tbar.removeClass("bgRed");
	   }
	 })
 	Ext.getCmp(topMenuId).addClass("bgRed");
 	Ext.getCmp(topMenuId).setDisabled(true);	
	//根据topMenuId刷新左边的菜单
	var tree = Ext.getCmp(Global.STD_WEST_MENU.id);
    setTimeout(function() {
		tree.getLoader().dataUrl = 'admin/system/IndexAction!listMenu.action?menuId='+topMenuId;
		tree.getLoader().load(tree.root);},300);
	//加载点击的菜单对应的窗体	
	destroyAllOfNewWinArray();
 	Ext.StoreMgr.clear();
	var postdata = {};
	AjaxDelegate(url, portal.callback, postdata,'return','');
	
}

function showShourCut() {

	var tree = new Ext.tree.TreePanel({
		id:'menuTree',
	//	maxNodeNum:45,
		maxNodeNum:21,
		region:'center', 
		//checkModel: 'cascade',
	    onlyLeafCheckable: true,//对树叶子可选 
	    animate: false, 
	    autoScroll:true,
	    getChecked :function(node){
	    	
			var checked = [], i;
			if( typeof node == 'undefined' ) {
				node = this.rootVisible ? this.getRootNode() : this.getRootNode().firstChild;
			}
			if( node.attributes.checked) {
			    var alias = document.getElementById(node.id + "-alias");
			    var aliasValue = "null";
//					    if(alias && alias != null) {
//					        var aliasValue = alias.value;
//					        if(aliasValue.trim() == "请自定义快捷方式名称" || aliasValue.trim() == "") {
//					            aliasValue = "null";
//					        }
//					    }
//						checked.push(node.id + "|" + aliasValue);
				checked.push(node.id);
			}
			if( !node.isLeaf() ) {
				for( i = 0; i < node.childNodes.length; i++ ) {
					checked = checked.concat( this.getChecked(node.childNodes[i]) );
				}
			}
			return checked;
		},
		
	    loader: new Ext.tree.TreeLoader({ 
	    	dataUrl: 'admin/system/ShortcutAction!getRights.action',
	        preloadChildren:true,
	        baseAttrs: { uiProvider: Ext.tree.TreeCheckNodeUI } //添加 uiProvider 属性 
	    }), 
	    root: new Ext.tree.AsyncTreeNode({ expanded:true,id :"root",text:"VASMS" })
	});		
			
	var  win = new VAS.BasicWindow({
		title  : '桌面设置',
		width  : 500,
		height : 500,
		layout : "fit",
		items  : [tree],
		modal  : true,
		draggable  : true,
		closable   : true,
		buttons:[{
			xtype  : 'button',
			text   : '保存并关闭',
			handler: function() {
					var checked = tree.getChecked();
					var ids=checked.join(',');
					Ext.Ajax.request({
						url:'admin/system/ShortcutAction!saveShortcut.action',
						params:{menuIds:ids},
						success:function(response){
						  //检查session是否过期
						  checkTimeOut(response);
						  var responseObj=Ext.decode(response.responseText);
						  if(responseObj.success){
								win.close();
								homePage();  //重新装载首页
							}else{
								alertFailure(responseObj);
							}
						},
						failure:function(){
							Ext.Msg.alert("提示","服务器异常！");
						}
					});
					
			}
		},{
			xtype : 'button'
			,text : '关闭'
			,handler : function(){
				win.close();
			}
		}]
	}).show();
		
	tree.on("check",function(node,checked){
			var tree = node.getOwnerTree();
			var alias = document.getElementById(node.id + "-alias");
			if(checked){
				var checked=tree.getChecked();
				node.attributes.checked=true;
				//alias.style.display = "inline";
				if(checked.length>tree.maxNodeNum){
					node.ui.checkbox.checked=false;
					node.attributes.checked=false;
					alias.style.display = "none";
					
					Ext.Msg.alert('提示','最多可选择'+tree.maxNodeNum+'个菜单作为快捷方式');
				}
			}else{
				node.attributes.checked=false;
				alias.style.display = "none";
			}
		});
}
